<template>
  <div class="banner-container" @mouseenter="autoStop" @mouseleave="autoStart">
    <ul
      class="images"
      :style="{
        width: banners.length * 100 + '%',
        marginLeft: -index * 100 + '%',
      }"
    >
      <li v-for="(item, i) in banners" :key="i">
        <a :href="item.link"><img :src="item.url" alt="" /></a>
      </li>
    </ul>
    <ul class="dots">
      <li
        v-for="(item, i) in banners"
        :key="i"
        :class="{
          active: i === index,
        }"
        @click="index = i"
      ></li>
    </ul>
  </div>
</template>

<script>
export default {
  props: {
    banners: {
      type: Array, // 属性类型是数组
      required: true // 必须要传递该属性
    },
    duration: {
      type: Number,
      default: 2000 // 属性默认值
    }
  },
  data () {
    return {
      index: 0, // 当前显示图片的下标
      timer: null
    }
  },
  created () {
    // console.log('组件创建了...')
    this.autoStart()
  },
  // updated () {
  //   console.log('组件重新渲染了...')
  // },
  destroyed () {
    // console.log('组件被销毁了...')
    this.autoStop()
  },
  methods: {
    // 自动开始切换
    autoStart () {
      if (this.timer) {
        return
      }
      this.timer = setInterval(() => {
        // console.log('切换')
        this.index = (this.index + 1) % this.banners.length
      }, this.duration)
    },
    // 停止自动切换
    autoStop () {
      clearInterval(this.timer)
      this.timer = null
    }
  }
}
</script>

<style scoped lang="scss">
/* 样式 */
.banner-container {
  height: 350px;
  position: relative;
  overflow: hidden;
  li {
    display: block;
    width: 1080px;
    height: 100%;
    float: left;
  }
  img {
    width: 1080px;
    height: 100%;
  }
}
.images {
  height: 100%;
  transition: 0.5s;
}
.dots {
  position: absolute;
  bottom: 10px;
  right: 10px;
  display: flex;
  li {
    width: 10px;
    height: 10px;
    cursor: pointer;
    margin: 0 3px;
    border-radius: 50%;
    border: 1px solid;
    color: #fff;
    &.active {
      background: #fff;
    }
  }
}
</style>
